//
//  WebBrowser.m
//  BehindTheMask
//
//  Created by Basuke on 08/03/15.
//  Copyright 2008 Basuke's. All rights reserved.
//

#import "WebBrowser.h"
#import "BuilderHelper.h"
#import "Console.h"

#define kTopMargin 20


@implementation WebBrowser

@synthesize webView;
@synthesize urlField;

- (id)init
{
	if (self = [super init]) {
		// Initialize your view controller.
		self.title = @"Web";
		self.toolbarItem.image = [UIImage imageNamed:@"World.png"];
	}
	return self;
}

- (void)loadView
{
	UIView *view = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
	view.backgroundColor = [UIColor whiteColor];
	view.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
	view.autoresizesSubviews = YES;
	
	self.view = view;
	
	webView = [BuilderHelper webViewWithMarginTop:(kTopMargin + 5.0)];
	webView.delegate = self;
	[self.view addSubview: webView];
	[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://kanshin.jp"]]];
	
	// left button
	UIButton *button = [BuilderHelper buttonWithImage:@"LeftArrow.png" highlightImage:@"LeftArrowPressed.png" at:CGPointMake(5.0, 10.0)];
	[button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:button];
	
	// right button
	button = [BuilderHelper buttonWithImage:@"RightArrow.png" highlightImage:@"RightArrowPressed.png" at:CGPointMake(45.0, 10.0)];
	[button addTarget:self action:@selector(forwardAction:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:button];
	
	// reload button
	button = [BuilderHelper buttonWithImage:@"reload.png" highlightImage:@"reload_tap.png" at:CGPointMake(85.0, 10.0)];
	[button addTarget:self action:@selector(reloadAction:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:button];
	
	urlField = [BuilderHelper urlFieldAt:CGPointMake(120.0, 10.0) width:self.view.bounds.size.width - 130];
    urlField.delegate = self;
	[self.view addSubview:urlField];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[textField text]]]];
	return YES;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
	[[Console sharedConsole] log:[NSString stringWithFormat:@"shouldStartLoadWithRequest(%@, %d)", request, navigationType]];
	return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
	[[Console sharedConsole] log:@"webViewDidStartLoad"];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
	[[Console sharedConsole] log:@"webViewDidFinishLoad"];
	
	[[Console sharedConsole] dumpViewHierarchy:self.view];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
	[[Console sharedConsole] log:[NSString stringWithFormat:@"didFailLoadWithError(%@)", error]];
}

@end
